﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Ionic.Zip;

namespace WebPALTT.Lib
{
    public class FileImport
    {
        /// <summary>
        /// Opens a Fiddler2 session archive file, returning a user session containing the request from the archive.
        /// </summary>
        /// <param name="path">The file path of the session archive</param>
        /// <returns>A user session containing the request from the archive</returns>
        public static ActionItemCollection Import(String path)
        {
            ActionItemCollection items = new ActionItemCollection();

            using (ZipFile zip1 = ZipFile.Read(path))
            {
                foreach (ZipEntry e in zip1)
                {
                    if (e.FileName.EndsWith("_c.txt"))
                    {
                        String name = e.FileName.Substring(4, e.FileName.Length - 10);
                        Stream txtStream = e.OpenReader();
                        items.Add(CreateWebRequest(name, (new StreamReader(txtStream)).ReadToEnd()));
                    }
                }
            }
            return items;
        }

        static ActionItem CreateWebRequest(String name, String html)
        {
            String method;
            String protocol = "1.0";
            Uri uri;
            List<KeyValuePair<String, String>> headerList = new List<KeyValuePair<string, string>> { };

            int startIndex = html.IndexOf("\r\n\r\n");
            String body = html.Substring(startIndex + 4);
            String[] headers = html.Substring(0, startIndex).Split(new String[] { "\r\n" }, StringSplitOptions.None);

            if (headers[0].EndsWith("HTTP/1.1"))
                protocol = "1.1";

            if (headers[0].StartsWith("POST"))
            {
                uri = new Uri(headers[0].Substring(5, headers[0].Length - 14));
                method = "POST";
            }
            else if (headers[0].StartsWith("GET"))
            {
                uri = new Uri(headers[0].Substring(4, headers[0].Length - 13));
                method = "GET";
            }
            else
                throw new Exception("Invalid HTML Header");

            foreach (String head in headers)
            {
                if (head.ToLower().StartsWith("post") || head.ToLower().StartsWith("get"))
                    continue;
                else if (head.ToLower().StartsWith("cookie"))
                    continue;
                else
                {
                    int index = head.IndexOf(": ");
                    headerList.Add(new KeyValuePair<string, string>(head.Substring(0, index), head.Substring(index + 2)));
                }
            }

            ActionItem_WebRequest reqDef = new ActionItem_WebRequest(name, method, uri, protocol, headerList.ToArray(), body);

            return reqDef;
        }
    }

    /// <summary>
    /// Static class to serialize and deserialize objects and files.     /// 
    /// </summary>
    public static class FileSerialization
    {
        public static void SerializeObject<T>(T test, string path)
        {
            Stream stream = File.Open(path, FileMode.Create);
            BinaryFormatter bFormatter = new BinaryFormatter();
            bFormatter.Serialize(stream, test);
            stream.Close();
        }

        public static T DeSerializeObject<T>(string path)
        {
            T test;
            Stream stream = File.Open(path, FileMode.Open);
            BinaryFormatter bFormatter = new BinaryFormatter();
            test = (T)bFormatter.Deserialize(stream);
            stream.Close();
            return test;
        }
    }
}
